package com.ruiyangwang.ListenBook.repository;

import com.ruiyangwang.ListenBook.dataObject.UserDo;
import com.ruiyangwang.ListenBook.util.DButil;
import com.ruiyangwang.ListenBook.util.Log;
import lombok.SneakyThrows;

import java.sql.*;

/**
 * @author syzygy
 * @date 2022/07/09 15:23
 * 负责使用sql对sql进行CURD操作
 **/
public class UserRepo {
    @SneakyThrows
    public void insert(UserDo userDo){
        String sql = "insert into users(username,password) values (?,?)";
        try(Connection c = DButil.connection()){
            try(PreparedStatement ps = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)){
                ps.setString(1,userDo.username);
                ps.setString(2,userDo.password);
                Log.println("执行sql语句：" + ps.toString());
                ps.executeUpdate();

                try(ResultSet rs = ps.getGeneratedKeys()){
                    rs.next();
                    userDo.uid = rs.getInt(1);
                }
            }
        }

    }

    public UserDo selectOneByUsername(String username) throws SQLException {
        String sql = "select uid , username,password from users where username = ?";
        try(Connection c = DButil.connection()){
            try(PreparedStatement ps = c.prepareStatement(sql)){
                ps.setString(1,username);
                Log.println("执行sql语句：" + ps.toString());
                try(ResultSet rs = ps.executeQuery()){
                    if(!rs.next()){
                        return null;
                    }
                    return new UserDo(
                            rs.getInt("uid"),
                            rs.getString("username"),
                            rs.getString("password")
                    );

                }
            }
        }
    }
}